<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use App\Http\Model\Room;
use App\Http\Model\Union;
use App\Http\Model\FinanceKk;

class UnionRoomWeekReward extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'unionRoomWeekReward';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '公会房间周结算奖励';

    protected $unionTable = "union";
    protected $unionRoomTable = 'union_room';
    protected $unionRoomStreamTable = 'finance_union_room_stream';
    protected $unionRoomWeekrewardTable = 'union_room_weekreward';
    protected $financeWalletTable = 'finance_wallet';
    protected $userTable = 'user';
    protected $roomTable = 'room';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $time = time();
        $unionModel = new Union();
        $roomModel = new Room();
        $modelFinanceKk = new FinanceKk();

        //上周的日期
        $day = getWeekTimestamp(1, 0);
        $time_st = $day[0].' 00:00:00';
        $time_ed = $day[1].' 23:59:59';

        do {
            //所有联盟
            $unionList = $unionModel->getAllUnion();
            foreach($unionList as $union) {
                //周结奖励
                if($union['reward_type'] != 0) {
                    continue;
                }

                $extraRoom = [];//额外奖励记录
                $stepRoom = [];//阶梯奖励记录
                $roomLogs = [];//记录房间信息
                //联盟房间
                $rooms = DB::table($this->unionRoomTable)->where('un_id', $union['id'])
                    ->leftJoin("room", "room.room_id", "=", "union_room.room_id")
                    ->select('room.*')
                    ->get();
                $rooms = $this->objToArray($rooms);
                if(empty($rooms)) {
                    continue;
                }
                //去除非BCD房间
                $roomList = [];
                foreach($rooms as $room) {
                    if($room['business_type'] == 1) {
                        $roomList[] = $room;
                    }
                }
                //获取房间收入
                $roomTotal = DB::table($this->unionRoomStreamTable)
                    ->selectRaw('room_id, sum(data_value * data_num) as num')
                    ->where('created_at', '>=', $time_st)
                    ->where('created_at', '<=', $time_ed)
                    ->where('union_id', $union['id'])
                    ->groupBy("room_id")
                    ->get();
                $roomTotal = $this->objToArray($roomTotal);
                $roomTotal = array_column($roomTotal, 'num', 'room_id');

                //房间流水合计
                $unionTotalSum = 0;
                foreach($roomList as $room) {
                    if($room['business_type'] != 1) {
                        continue;
                    }
                    //房间周消费钻石数
                    $totalSum = empty($roomTotal[$room['room_id']]) ? 0 : $roomTotal[$room['room_id']];
                    $unionTotalSum = $unionTotalSum + $totalSum;
                }

                //阶梯奖励
                //大于等于20万钻石（1%）    大于等于80万钻石（1.5%）    大于等于200万钻石（3%）
                if($unionTotalSum < 200000){
                    $rate = 0;
                }elseif($unionTotalSum>=200000 && $unionTotalSum<500000){
                    $rate = 0.01;
                }elseif($unionTotalSum>=500000 && $unionTotalSum<1000000){
                    $rate = 0.02;
                }elseif($unionTotalSum >= 1000000){
                    $rate = 0.03;
                }
                $roomTotal = intval($unionTotalSum*$rate);
                $stepRate = round($rate*100);

                $ratioConf = config('pay');
                $desc2 = $ratioConf['wallet_change_desc']['room_gift_union_kk_1'];
                if($roomTotal > 0) {
                    $modelFinanceKk->inc($union['un_user_id'], 0, 0, 31, $roomTotal, $desc2);
                }

                //日志记录
                $item = [];
                $item['date'] = date("Ymd", strtotime($time_st));
                $item['union_id'] = $union['id'];
                $item['room_id'] = 0;
                $item['roomTotal'] = $unionTotalSum;
                $item['stepRate'] = $stepRate;
                $item['stepTotal'] = $roomTotal;
                $item['extraRate'] = 0;
                $item['extraTotal'] = 0;
                $item['inviteTotal'] = 0;
                $item['inviteRewardTotal'] = 0;

                if($item['roomTotal'] > 0) {
                    DB::table($this->unionRoomWeekrewardTable)->insertGetId($item); 
                }

                /*
                //阶梯奖励
                foreach($roomList as $room) {
                    if($room['business_type'] != 1) {
                        continue;
                    }
                    //房间周消费钻石数
                    $totalSum = empty($roomTotal[$room['room_id']]) ? 0 : $roomTotal[$room['room_id']];
                    //大于等于20万钻石（1%）    大于等于80万钻石（1.5%）    大于等于200万钻石（3%）
                    if($totalSum < 200000){
                        $rate = 0;
                    }elseif($totalSum>=200000 && $totalSum<800000){
                        $rate = 0.01;
                    }elseif($totalSum>=800000 && $totalSum<2000000){
                        $rate = 0.015;
                    }elseif($totalSum >= 2000000){
                        $rate = 0.03;
                    }
                    $stepRoom[$room['room_id']] = intval($totalSum*$rate);
                    $roomLogs[$room['room_id']]['stepRate'] = round($rate*100);
                    $roomLogs[$room['room_id']]['stepTotal'] = $stepRoom[$room['room_id']];
                }

                //日志记录
                $log = ['union_id'=>$union['id'], 'roomTotal'=>$roomTotal,'inviteUserIds'=>0,'inviteRoomTotal'=>0, 'stepRoom'=>[], 'effectiveRoom'=>[], 'extraRoom'=>$extraRoom, 'inviteRoom'=>0];
                write_log('unionRoomWeekReward', 'info', $log);

                $ratioConf = config('pay');
                $desc2 = $ratioConf['wallet_change_desc']['room_gift_union_kk_1'];
                
                //发阶梯奖励
                foreach($stepRoom as $room_id=>$kk_value) {
                    if($kk_value > 0) {
                        $modelFinanceKk->inc($union['un_user_id'], 0, $room_id, 31, $kk_value, $desc2);
                    }
                }

                //防重复
                unset($stepRoom);

                //日志记录
                foreach($roomList as $room) {
                    $item = [];
                    $item['date'] = date("Ymd", strtotime($time_st));
                    $item['union_id'] = $union['id'];
                    $item['room_id'] = $room['room_id'];
                    $item['roomTotal'] = empty($roomTotal[$room['room_id']]) ? 0 : $roomTotal[$room['room_id']];
                    $item['stepRate'] = empty($roomLogs[$room['room_id']]['stepRate']) ? 0 : $roomLogs[$room['room_id']]['stepRate'];
                    $item['stepTotal'] = empty($roomLogs[$room['room_id']]['stepTotal']) ? 0 : $roomLogs[$room['room_id']]['stepTotal'];
                    $item['extraRate'] = empty($roomLogs[$room['room_id']]['extraRate']) ? 0 : $roomLogs[$room['room_id']]['extraRate'];
                    $item['extraTotal'] = empty($roomLogs[$room['room_id']]['extraTotal']) ? 0 : $roomLogs[$room['room_id']]['extraTotal'];
                    $item['inviteTotal'] = empty($roomLogs[$room['room_id']]['inviteTotal']) ? 0 : $roomLogs[$room['room_id']]['inviteTotal'];
                    $item['inviteRewardTotal'] = empty($roomLogs[$room['room_id']]['inviteRewardTotal']) ? 0 : $roomLogs[$room['room_id']]['inviteRewardTotal'];

                    if($item['roomTotal'] > 0) {
                        DB::table($this->unionRoomWeekrewardTable)->insertGetId($item); 
                    }
                }
                */
            }
        } while (false);
    }

    //返回数组
    public function objToArray($document)
    {
        return json_decode(json_encode($document), true);
    }

}